#!/usr/bin/env node

const request = require('superagent');
const shell = require('shelljs');
const mockjs = require('mockjs');
const utils = require('./js/utils');
const readline = require('readline');
const program = require('./js/dialog').commander();
const logFile = require('path').join(require('os').homedir(), '.xn_history', '.xn_xpost_history');
const paramsFile = require('path').join(require('os').homedir(), '.xn_history', '.xn_xpost_params');
let $ = utils.getFileJSON(paramsFile);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

program
.version('0.0.1')
.option('-u, --url [http://127.0.0.1:3000/test]', 'url of api')
.option('-i, --ip [127.0.0.1]', 'server ip of api', '127.0.0.1')
.option('-p, --port [3000]', 'server port of api', '3000')
.option('-t, --path [/]', 'server path of api', '/')
.option('-d, --data <json>', 'data must be json format', (v)=>eval('v='+v), {})
.option('-f, --format <json>', 'Accept Format:[json, text]', 'json')
.option('-l, --log [n|text]', 'show log n items, default: 10, 或者通过text搜索')
.option('-s, --save [n]', '保存参数: -s roleId xxx，使用参数 -d {id: $.roleId}')
.option('支持mock -d {name:\'@first\'}', '基础:boolean,natural,integer,float,character,string,range,date,time,datetime,now|图片:image,dataImage|颜色:color|文字:paragraph,sentence,word,title,cparagraph,csentence,cword,ctitle|名字:first,last,name,cfirst,clast,cname|网页:url,domain,email,ip,tld|地址:area,region|编号:guid,id')
.parse(process.argv);

let { url, ip, port, path, log, data, format, save } = program;
if (!url) {
    url = `http://${ip}:${port}${path[0]!=='/'?'/':''}${path}`;
}
if (log) {
    if (log === true)
        log = '10';
    const content = /^\d+$/.test(log) ? shell.tail({'-n': log}, logFile).toString() : shell.cat(logFile).toString();
    let lines = content.split('\n');
    if (!/^\d+$/.test(log)) {
        lines = lines.filter(line => utils._r(log, 'i').test(line));
    }
    console.log(lines.map((o, i)=>`${i}: ${o}`).join('\n'));
    // 示例：询问用户名并等待输入
    rl.question('input index copy(q: exit)：', (index) => {
        if (lines[index]) {
            utils.copy(lines[index]);
            console.log('已复制到剪切板');
        }
        process.exit(0);
    });
} else {
    if (save) {
        if (!process.argv[3]) {
            console.log('现有参数：');
            console.log(utils.stringify($, 2));
            console.log('\n设置格式：xpost -s key value');
        } else {
            $ = { ...$, [process.argv[3]]: process.argv[4] };
            console.log('更新参数：');
            console.log(utils.stringify($, 2));
            utils.logToFile(paramsFile, $);
        }
        process.exit(0);
    }
    data = mockjs.mock(data);
    console.log('发送的参数:', data);
    request
    .post(url)
    .set({
        'Accept': 'application/json',
        'Content-Type': format === 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + ($.token || '').replace(/\s*bearer\s*/i, ''),
    })
    .send(data)
    .end((error, res) => {
        if (error) {
            console.error(`[${url}] recv error:`, error.status);
        } else if (format === 'json') {
            console.log(JSON.stringify(res.body, null, 2));
        } else {
            console.log(res.text);
        }
        utils.saveHistory(logFile, `xpost -u ${url} -d "${utils.stringify(data, 2)}"`);
        process.exit(0);
    });
}
